import path from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy' // 这个插件依赖 pnpm  add terser
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import px2viewport from 'postcss-px-to-viewport'
import autoprefixer from 'autoprefixer'
const px2vwOptions = (viewportWidth, excludePattern) => ({
  unitToConvert: 'px',
  viewportWidth,
  unitPrecision: 6,
  propList: ['*'],
  viewportUnit: 'vw',
  fontViewportUnit: 'vw',
  selectorBlackList: [],
  minPixelValue: 1,
  mediaQuery: true,
  replace: true,
  exclude: [excludePattern],
  landscape: false
})

export default defineConfig({
  plugins: [
    vue(),
    legacy({
      targets: ['defaults', 'not IE 11', 'chrome 52']
    }),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      symbolId: 'icon-[dir]-[name]',
      customDomId: '__svg__icons__dom__'
    })
  ],
  css: {
    postcss: {
      plugins: [px2viewport(px2vwOptions(375, /^(?!.*node_modules\/vant)/)), px2viewport(px2vwOptions(750, /node_modules\/vant/i)),autoprefixer({
        overrideBrowserslist: [
          'Android 4.1',
          'iOS 7.1',
          'Chrome > 31',
          'ff > 31',
          'ie >= 8',
          '> 1%',]
      })]
    }
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  build: {
    chunkSizeWarningLimit: 3000,
    outDir: 'dist',
    assetsDir: 'assets', //指定静态资源存放路径
    sourcemap: false, //是否构建source map 文件
    emptyOutDir: true, // 是否清空目录
    // 去除console 和 debugger
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    },
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor'
          }
        },
        entryFileNames: 'js/[name].[hash].js',
        chunkFileNames: 'js/[name].[hash].js',
        assetFileNames: ({ name }) => {
          if (/\.(gif|jpe?g|png|svg)$/.test(name ?? '')) {
            return 'img/[name].[hash][extname]';
          }
          if (/\.css$/.test(name ?? '')) {
            return 'css/[name].[hash][extname]';
          }
          if (/\.(woff2?|eot|ttf|otf)$/.test(name ?? '')) {
            return 'font/[name].[hash][extname]';
          }
          return 'other/[name].[hash][extname]';
        },
      }
    }
  },
  server: {
    host: '0.0.0.0'
    //  proxy: {
    //  '/api': {
    //     target: 'http://192.168.0.210:80',
    //     changeOrigin: true,
    //     rewrite: (path) => path.replace(/^\/api/, '/api'),
    //    },
    //  },
  }
})
